<template>
  <div class="score-container">
    <!-- 学生成绩查询页面 -->
    <div v-if="userRole === 0" class="student-score-view">
      <div class="page-header">
        <h2>成绩查询</h2>
        <div class="header-actions">
          <el-select
            v-model="selectedCourse"
            placeholder="选择课程"
            clearable
            style="width: 200px; margin-right: 10px;"
            @change="handleSearch"
          >
            <el-option
              v-for="course in courseList"
              :key="course.id"
              :label="course.fullCourseName || course.name"
              :value="course.id"
            />
          </el-select>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
        </div>
      </div>
      
      <!-- 成绩统计卡片 -->
      <div class="stats-cards">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-number">{{ totalScores }}</div>
              <div class="stat-label">总成绩数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-number">{{ weightedAverageScore }}</div>
              <div class="stat-label">加权平均分</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-number">{{ passedCount }}</div>
              <div class="stat-label">及格科目</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-number">{{ failedCount }}</div>
              <div class="stat-label">不及格科目</div>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <!-- 成绩表格 -->
      <div class="scores-table">
        <el-table
          :data="scoresList"
          v-loading="loading"
          stripe
          style="width: 100%"
        >
          <template #empty>
            <el-empty
              description="暂无成绩数据"
              :image-size="100"
            >
              <template #description>
                <p>还没有成绩记录</p>
                <p v-if="selectedCourse">请尝试选择其他课程或清空筛选条件</p>
              </template>
            </el-empty>
          </template>
          <el-table-column prop="fullCourseName" label="课程" width="180">
            <template #default="{ row }">
              {{ row.fullCourseName || row.courseName }}
            </template>
          </el-table-column>
          <el-table-column prop="courseCode" label="课程代码" width="120" />
          <el-table-column prop="score" label="成绩" width="100">
            <template #default="{ row }">
              <el-tag
                :type="getScoreType(row.score)"
                effect="plain"
              >
                {{ row.score }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="credits" label="学分" width="80" />
          <el-table-column prop="examDate" label="考试日期" width="120" />
          <el-table-column prop="fullClassName" label="班级" width="150">
            <template #default="{ row }">
              {{ getClassDisplayName(row) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag
                :type="row.score >= 60 ? 'success' : 'danger'"
                size="small"
              >
                {{ row.score >= 60 ? '及格' : '不及格' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="120">
            <template #default="{ row }">
              {{ row.remark || '-' }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    
    <!-- 管理员成绩管理页面 -->
    <div v-else class="admin-score-view">
      <div class="page-header">
        <h2>成绩管理</h2>
        <div class="header-actions" v-if="userRole !== 0">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            录入成绩
          </el-button>
          <!-- <el-button type="success" @click="handleImport">
            <el-icon><Upload /></el-icon>
            批量导入
          </el-button>
          <el-button type="warning" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出成绩
          </el-button> -->
        </div>
      </div>
      
      <!-- 搜索筛选 -->
      <div class="search-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-select
              v-model="searchForm.classId"
              placeholder="选择班级"
              clearable
              @change="handleSearch"
            >
              <el-option label="全部班级" value="" />
              <el-option
                v-for="cls in classList"
                :key="cls.id"
                :label="getClassDisplayName(cls)"
                :value="cls.id"
              />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="searchForm.courseId"
              placeholder="选择课程"
              clearable
              @change="handleSearch"
            >
              <el-option label="全部课程" value="" />
              <el-option
                v-for="course in courseList"
                :key="course.id"
                :label="course.fullCourseName || course.name"
                :value="course.id"
              />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="searchForm.studentName"
              placeholder="学生姓名"
              clearable
              @input="debouncedSearch"
              @clear="handleSearch"
            />
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 管理员成绩表格 -->
      <div class="admin-scores-table">
        <el-table
          :data="adminScoresList"
          v-loading="loading"
          stripe
          style="width: 100%"
        >
          <template #empty>
            <el-empty
              description="暂无成绩数据"
              :image-size="100"
            >
              <template #description>
                <p>没有找到符合条件的成绩记录</p>
                <p>请尝试调整搜索条件或录入新的成绩</p>
              </template>
            </el-empty>
          </template>
          <el-table-column prop="sno" label="学号" width="150">
            <template #default="{ row }">
              {{ row.sno || row.studentId }}
            </template>
          </el-table-column>
          <el-table-column prop="studentName" label="学生姓名" width="150" />
          <el-table-column prop="fullClassName" label="班级" width="180">
            <template #default="{ row }">
              {{ getClassDisplayName(row) }}
            </template>
          </el-table-column>
          <el-table-column prop="fullCourseName" label="课程" width="180">
            <template #default="{ row }">
              {{ row.fullCourseName || row.courseName }}
            </template>
          </el-table-column>
          <el-table-column prop="score" label="成绩" width="120">
            <template #default="{ row }">
              <el-tag
                :type="getScoreType(row.score)"
                effect="plain"
              >
                {{ row.score }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="credits" label="学分" width="100" />
          <el-table-column prop="examDate" label="考试日期" width="150" />
          <el-table-column prop="remark" label="备注" width="150">
            <template #default="{ row }">
              {{ row.remark || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="120">
            <template #default="{ row }">
              <el-tag
                :type="row.score >= 60 ? 'success' : 'danger'"
                size="small"
              >
                {{ row.score >= 60 ? '及格' : '不及格' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300" fixed="right" v-if="userRole !== 0">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 成绩录入/编辑对话框 - 仅管理员可见 -->
    <ScoreDialog
      v-if="userRole !== 0"
      v-model:visible="scoreDialogVisible"
      :score-data="currentScoreData"
      :student-list="studentList"
      :course-list="courseList"
      @success="handleScoreSuccess"
    />

    <!-- 批量导入对话框 - 仅管理员可见 -->
    <el-dialog
      v-if="userRole !== 0"
      v-model="importDialogVisible"
      title="批量导入成绩"
      width="600px"
    >
      <div class="import-content">
        <el-alert
          title="导入说明"
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        >
          <template #default>
            <p>1. 请下载导入模板，按照模板格式填写数据</p>
            <p>2. 支持Excel文件格式(.xlsx, .xls)</p>
            <p>3. 文件大小不超过10MB</p>
            <p>4. 学生ID和课程ID必须是系统中已存在的</p>
          </template>
        </el-alert>

        <div class="template-download" style="margin-bottom: 20px;">
          <el-button type="primary" @click="downloadTemplate">
            <el-icon><Download /></el-icon>
            下载导入模板
          </el-button>
        </div>

        <el-upload
          ref="uploadRef"
          class="upload-demo"
          drag
          :before-upload="handleFileUpload"
          :on-success="handleUploadSuccess"
          :show-file-list="false"
          accept=".xlsx,.xls"
        >
          <el-icon class="el-icon--upload"><Upload /></el-icon>
          <div class="el-upload__text">
            将Excel文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传xlsx/xls文件，且不超过10MB
            </div>
          </template>
        </el-upload>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useUserStore } from '@/store/modules/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Plus,
  Upload,
  Download
} from '@element-plus/icons-vue'
import ScoreDialog from '@/components/ScoreDialog.vue'
import {
  deleteScoreApi,
  getScorePageApi,
  calculateStudentAverageApi,
  batchImportScoresApi
} from '@/api/score/score'
import { getStudentsApi } from '@/api/student/student'
import { getAllCoursesApi } from '@/api/course/course'
import { getClassOptionsApi } from '@/api/class/class'

const userStore = useUserStore()

// 用户角色
const userRole = computed(() => {
  // 优先使用数字格式的role
  let role = userStore.userInfo?.role

  // 如果没有role，从userType转换
  if (role === undefined || role === null) {
    const userType = userStore.userInfo?.userType
    if (userType === 'student') role = 0
    else if (userType === 'admin') role = 1
    else if (userType === 'super_admin') role = 2
    else role = 0 // 默认为学生
  }



  return role
})

// 响应式数据
const loading = ref(false)
const selectedCourse = ref('')
const courseList = ref([])
const classList = ref([])
const scoresList = ref([])
const adminScoresList = ref([])
const studentList = ref([])

// 对话框相关
const scoreDialogVisible = ref(false)
const currentScoreData = ref({})

// 搜索防抖
let searchTimer = null

// 批量导入相关
const importDialogVisible = ref(false)
const uploadRef = ref()
const importLoading = ref(false)

// 搜索表单
const searchForm = reactive({
  classId: '',
  courseId: '',
  studentName: ''
})

// 分页
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 模拟数据
const mockCourses = [
  { id: 1, name: '高等数学' },
  { id: 2, name: '大学英语' },
  { id: 3, name: '计算机基础' },
  { id: 4, name: '数据结构' },
  { id: 5, name: '操作系统' }
]

const mockClasses = [
  { id: 1, name: '（1）班', grade: '2021', fullClassName: '2021级（1）班' },
  { id: 2, name: '（2）班', grade: '2021', fullClassName: '2021级（2）班' },
  { id: 3, name: '（1）班', grade: '2022', fullClassName: '2022级（1）班' },
  { id: 4, name: '（2）班', grade: '2022', fullClassName: '2022级（2）班' },
  { id: 5, name: '（3）班', grade: '2023', fullClassName: '2023级（3）班' }
]

const mockStudentScores = [
  {
    id: 1,
    courseName: '高等数学',
    courseCode: 'MATH001',
    score: 85,
    credit: 4,
    examType: '期末考试',
    examDate: '2024-01-15',
    semester: '2023-2024-1',
    remark: '良好'
  },
  {
    id: 2,
    courseName: '大学英语',
    courseCode: 'ENG001',
    score: 78,
    credit: 3,
    examType: '期末考试',
    examDate: '2024-01-18',
    semester: '2023-2024-1',
    remark: ''
  },
  {
    id: 3,
    courseName: '计算机基础',
    courseCode: 'CS001',
    score: 92,
    credit: 3,
    examType: '期末考试',
    examDate: '2024-01-20',
    semester: '2023-2024-1',
    remark: '优秀'
  },
  {
    id: 4,
    courseName: '数据结构',
    courseCode: 'CS002',
    score: 56,
    credit: 4,
    examType: '期末考试',
    examDate: '2024-01-22',
    semester: '2023-2024-1',
    remark: '需要补考'
  }
]

const mockAdminScores = [
  {
    id: 1,
    sno: 'S2021001',
    studentId: '2021001',
    studentName: '张三',
    className: '（1）班',
    fullClassName: '2021级（1）班',
    grade: '2021',
    courseName: '高等数学',
    fullCourseName: 'MATH001-高等数学',
    courseCode: 'MATH001',
    score: 85,
    credits: 4,
    examDate: '2024-01-15',
    remark: '期末考试'
  },
  {
    id: 2,
    sno: 'S2021002',
    studentId: '2021002',
    studentName: '李四',
    className: '（1）班',
    fullClassName: '2021级（1）班',
    grade: '2021',
    courseName: '高等数学',
    fullCourseName: 'MATH001-高等数学',
    courseCode: 'MATH001',
    score: 78,
    credits: 4,
    examDate: '2024-01-15',
    remark: '期末考试'
  }
]

// 计算属性（学生用）
const totalScores = computed(() => scoresList.value.length)

const averageScore = computed(() => {
  if (scoresList.value.length === 0) return '0.0'
  const total = scoresList.value.reduce((sum, item) => {
    // 处理不同的分数字段名
    const score = item.score || item.scoreValue || 0
    return sum + Number(score)
  }, 0)
  return (total / scoresList.value.length).toFixed(1)
})

const passedCount = computed(() => {
  return scoresList.value.filter(item => {
    const score = item.score || item.scoreValue || 0
    return Number(score) >= 60
  }).length
})

const failedCount = computed(() => {
  return scoresList.value.filter(item => {
    const score = item.score || item.scoreValue || 0
    return Number(score) < 60
  }).length
})

// 计算加权平均分（考虑学分）
const weightedAverageScore = computed(() => {
  if (scoresList.value.length === 0) return '0.0'

  let totalScore = 0
  let totalCredits = 0

  scoresList.value.forEach(item => {
    const score = Number(item.score || item.scoreValue || 0)
    const credits = Number(item.credits || item.credit || 1) // 默认学分为1
    totalScore += score * credits
    totalCredits += credits
  })

  return totalCredits > 0 ? (totalScore / totalCredits).toFixed(1) : '0.0'
})

// 方法
const getScoreType = (score) => {
  if (score >= 90) return 'success'
  if (score >= 80) return 'primary'
  if (score >= 70) return 'warning'
  if (score >= 60) return 'info'
  return 'danger'
}

// 获取班级显示名称（年级+班级名称）
const getClassDisplayName = (cls) => {
  if (!cls) return ''

  // 如果已经有完整的班级名称，直接使用
  if (cls.fullClassName) {
    return cls.fullClassName
  }

  // 否则组合年级和班级名称
  if (cls.grade && cls.name) {
    return `${cls.grade}级${cls.name}`
  }

  // 备用显示
  return cls.name || cls.className || '未知班级'
}

const handleSearch = async () => {
  loading.value = true

  try {
    if (userRole.value === 0) {
      // 学生查询自己的成绩 - 使用分页查询接口，后端会自动过滤
      const params = {
        page: 1,
        pageSize: 1000 // 设置较大的页面大小以获取所有成绩
      }

      // 如果选择了课程，添加课程过滤
      if (selectedCourse.value) {
        params.courseId = selectedCourse.value
      }

      const res = await getScorePageApi(params)
      if (res.code === 200) {
        const data = res.data
        let scores = []

        if (data && typeof data === 'object') {
          // 处理分页数据结构
          scores = data.data || []
        } else if (Array.isArray(data)) {
          // 处理非分页数据
          scores = data
        }

        scoresList.value = scores
        ElMessage.success(`查询到 ${scores.length} 条成绩记录`)
      } else {
        ElMessage.error(res.message || '查询失败')
        // 使用模拟数据作为备选
        let scores = mockStudentScores
        if (selectedCourse.value) {
          const course = courseList.value.find(c => c.id === selectedCourse.value)
          if (course) {
            scores = scores.filter(s => s.courseName === course.name)
          }
        }
        scoresList.value = scores
      }
    } else {
      // 管理员分页查询
      const params = {
        page: currentPage.value, // 后端使用1开始的页码
        pageSize: pageSize.value
      }

      // 添加搜索条件
      if (searchForm.classId) {
        params.classId = searchForm.classId
      }
      if (searchForm.courseId) {
        params.courseId = searchForm.courseId
      }
      if (searchForm.studentName && searchForm.studentName.trim()) {
        params.search = searchForm.studentName.trim()
      }

      const res = await getScorePageApi(params)
      if (res.code === 200) {
        const data = res.data
        if (data && typeof data === 'object') {
          // 处理后端返回的分页数据结构
          // 数据结构: { data, currentPage, pageSize, totalCount, totalPages, hasPrev, hasNext, dataSize, empty }
          adminScoresList.value = data.data || []
          total.value = data.totalCount || 0

          // 更新分页状态
          currentPage.value = data.currentPage || 1
          pageSize.value = data.pageSize || 10

          console.log('分页数据加载成功:', {
            currentPage: data.currentPage,
            totalCount: data.totalCount,
            totalPages: data.totalPages,
            dataSize: data.dataSize
          })
        } else if (Array.isArray(data)) {
          // 处理非分页数据
          adminScoresList.value = data
          total.value = data.length
        } else {
          adminScoresList.value = []
          total.value = 0
        }
        ElMessage.success(`查询成功，共找到 ${total.value} 条记录`)
      } else {
        ElMessage.error(res.message || '查询失败')
        // 使用模拟数据作为备选，并应用筛选
        let filteredData = [...mockAdminScores]

        if (searchForm.classId) {
          filteredData = filteredData.filter(item => item.classId === searchForm.classId)
        }
        if (searchForm.courseId) {
          filteredData = filteredData.filter(item => item.courseId === searchForm.courseId)
        }
        if (searchForm.studentName && searchForm.studentName.trim()) {
          const name = searchForm.studentName.trim().toLowerCase()
          filteredData = filteredData.filter(item =>
            item.studentName && item.studentName.toLowerCase().includes(name)
          )
        }

        adminScoresList.value = filteredData
        total.value = filteredData.length
      }
    }
  } catch (error) {
    console.error('查询失败:', error)

    // 根据错误类型提供更具体的错误信息
    let errorMessage = '查询失败，请稍后重试'
    if (error.response) {
      switch (error.response.status) {
        case 401:
          errorMessage = '登录已过期，请重新登录'
          break
        case 403:
          errorMessage = '没有权限访问该数据'
          break
        case 404:
          errorMessage = '请求的资源不存在'
          break
        case 500:
          errorMessage = '服务器内部错误，请联系管理员'
          break
        default:
          errorMessage = error.response.data?.message || '查询失败，请稍后重试'
      }
    } else if (error.request) {
      errorMessage = '网络连接失败，请检查网络设置'
    }

    ElMessage.error(errorMessage)

    
    if (userRole.value === 0) {
      scoresList.value = mockStudentScores
      ElMessage.info('已切换到演示数据模式')
    } else {
      adminScoresList.value = mockAdminScores
      total.value = mockAdminScores.length
      ElMessage.info('已切换到演示数据模式')
    }
  } finally {
    loading.value = false
  }
}

const handleReset = () => {
  // 重置搜索表单
  Object.assign(searchForm, {
    classId: '',
    courseId: '',
    studentName: ''
  })

  // 重置学生端的课程选择
  selectedCourse.value = ''

  // 重置分页
  currentPage.value = 1

  // 重新查询
  handleSearch()
}

// 防抖搜索
const debouncedSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  searchTimer = setTimeout(() => {
    currentPage.value = 1 // 重置到第一页
    handleSearch()
  }, 500)
}

const handleAdd = () => {
  // 权限检查：只有管理员可以录入成绩
  if (userRole.value === 0) {
    ElMessage.warning('学生无权限进行此操作')
    return
  }
  currentScoreData.value = {}
  scoreDialogVisible.value = true
}

const handleImport = () => {
  // 权限检查：只有管理员可以批量导入
  if (userRole.value === 0) {
    ElMessage.warning('学生无权限进行此操作')
    return
  }
  importDialogVisible.value = true
}

const handleExport = () => {
  // 权限检查：只有管理员可以导出成绩
  if (userRole.value === 0) {
    ElMessage.warning('学生无权限进行此操作')
    return
  }

  // 导出当前查询结果
  if (adminScoresList.value.length === 0) {
    ElMessage.warning('没有数据可以导出')
    return
  }

  try {
    // 准备导出数据
    const exportData = adminScoresList.value.map(item => ({
      '学号': item.studentId || item.sno,
      '学生姓名': item.studentName || item.name,
      '班级': item.className || item.class,
      '课程名称': item.courseName || item.course,
      '成绩': item.score,
      '考试日期': item.examDate,
      '学期': item.semester || '',
      '备注': item.remark || ''
    }))

    // 创建CSV内容
    const headers = Object.keys(exportData[0])
    const csvContent = [
      headers.join(','),
      ...exportData.map(row => headers.map(header => `"${row[header] || ''}"`).join(','))
    ].join('\n')

    // 创建下载链接
    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `成绩数据_${new Date().toISOString().slice(0, 10)}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 处理文件上传
const handleFileUpload = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                  file.type === 'application/vnd.ms-excel' ||
                  file.name.endsWith('.xlsx') ||
                  file.name.endsWith('.xls')

  if (!isExcel) {
    ElMessage.error('只能上传Excel文件!')
    return false
  }

  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!')
    return false
  }

  return true
}

// 文件上传成功处理
const handleUploadSuccess = async (file) => {
  importLoading.value = true

  try {
    // 这里应该解析Excel文件并转换为API需要的格式
    // 由于前端解析Excel比较复杂，这里提供一个简化的示例
    ElMessage.info('文件上传成功，正在处理...')

    // 模拟批量导入数据
    const mockImportData = [
      {
        studentId: 1,
        courseId: 1,
        score: 85.5,
        examDate: '2024-03-15',
        remark: '期中考试'
      }
    ]

    const res = await batchImportScoresApi(mockImportData)
    if (res.code === 200) {
      ElMessage.success('批量导入成功')
      importDialogVisible.value = false
      handleSearch() // 刷新数据
    } else {
      ElMessage.error(res.message || '导入失败')
    }
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败，请检查文件格式')
  } finally {
    importLoading.value = false
  }
}

// 下载导入模板
const downloadTemplate = () => {
  const templateData = [
    {
      '学生ID': '1',
      '课程ID': '1',
      '成绩': '85.5',
      '考试日期': '2024-03-15',
      '备注': '期中考试'
    }
  ]

  const headers = Object.keys(templateData[0])
  const csvContent = [
    headers.join(','),
    ...templateData.map(row => headers.map(header => `"${row[header]}"`).join(','))
  ].join('\n')

  const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.setAttribute('href', url)
  link.setAttribute('download', '成绩导入模板.csv')
  link.style.visibility = 'hidden'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)

  ElMessage.success('模板下载成功')
}

const handleEdit = (row) => {
  // 权限检查：只有管理员可以编辑成绩
  if (userRole.value === 0) {
    ElMessage.warning('学生无权限进行此操作')
    return
  }
  currentScoreData.value = { ...row }
  scoreDialogVisible.value = true
}

const handleDelete = async (row) => {
  // 权限检查：只有管理员可以删除成绩
  if (userRole.value === 0) {
    ElMessage.warning('学生无权限进行此操作')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除学生 ${row.studentName} 的 ${row.courseName} 成绩吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteScoreApi(row.id)
    ElMessage.success('删除成功')
    handleSearch() // 重新加载数据
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}

// 对话框成功回调
const handleScoreSuccess = () => {
  handleSearch() // 重新加载数据
}

// 加载学生统计信息
const loadStudentStats = async () => {
  if (userRole.value === 0) {
    const studentId = userStore.userInfo?.id
    if (studentId) {
      try {
        const res = await calculateStudentAverageApi(studentId)
        if (res.code === 200 && res.data) {
          // 可以在这里更新平均分显示，如果需要的话
          console.log('学生平均分:', res.data)
        }
      } catch (error) {
        console.error('获取学生平均分失败:', error)
      }
    }
  }
}

// 加载基础数据
const loadBasicData = async () => {
  try {
    // 加载课程列表
    const courseRes = await getAllCoursesApi()
    if (courseRes.code === 200) {
      courseList.value = courseRes.data || []
    }

    // 加载班级列表
    const classRes = await getClassOptionsApi()
    if (classRes.code === 200) {
      classList.value = classRes.data || []
    }

    // 加载学生列表（管理员需要）
    if (userRole.value !== 0) {
      const studentRes = await getStudentsApi()
      if (studentRes.code === 200) {
        studentList.value = studentRes.data?.data || []
      }
    }
  } catch (error) {
    console.error('加载基础数据失败:', error)
    // 使用模拟数据作为备选
    courseList.value = mockCourses
    classList.value = mockClasses
  }
}

const initData = async () => {
  await loadBasicData()
  // 初始化时加载成绩数据
  await handleSearch()
  // 加载统计信息
  await loadStudentStats()
}

onMounted(async () => {
  await initData()
})
</script>

<style lang="scss" scoped>
.score-container {
  width: 100%;
  max-width: 100%;
  margin: -20px; // 抵消父容器的padding
  padding: 20px; // 重新添加内边距

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: #333;
    }

    .header-actions {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .search-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    width: 100%;
  }

  .stats-cards {
    margin-bottom: 20px;
    width: 100%;

    .stat-card {
      background: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      text-align: center;

      .stat-number {
        font-size: 28px;
        font-weight: bold;
        color: #409eff;
        margin-bottom: 8px;
      }

      .stat-label {
        font-size: 14px;
        color: #666;
      }
    }
  }


  .scores-table,
  .admin-scores-table {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    overflow-x: auto; // 添加水平滚动支持

    // 确保表格占满容器宽度
    :deep(.el-table) {
      width: 100%;
      min-width: 800px; // 设置最小宽度确保内容不会过度压缩
    }

    // 优化表格单元格内容显示
    :deep(.el-table__cell) {
      padding: 12px 8px;
    }
    .el-table__body, .el-table__footer, .el-table__header {
    width: 100% !important;
  }
  }

  .pagination {
    display: flex;
    justify-content: center;
    padding: 20px 0;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .score-container {
    margin: -15px; // 移动端抵消父容器的padding
    padding: 15px; // 重新添加内边距

    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 15px;

      .header-actions {
        width: 100%;
        justify-content: flex-start;
        flex-wrap: wrap;
      }
    }

    .search-section {
      padding: 15px;

      .el-col {
        margin-bottom: 15px;
      }
    }

    .scores-table,
    .admin-scores-table {
      padding: 15px;

      // 移动端表格优化
      :deep(.el-table) {
        min-width: 600px; // 移动端减小最小宽度
        font-size: 14px;
      }

      // 操作按钮在移动端垂直排列
      :deep(.el-table__fixed-right) {
        .el-button {
          margin-bottom: 5px;
          display: block;
          width: 100%;
        }
      }
    }
  }
}

// 批量导入对话框样式
.import-content {
  .template-download {
    text-align: center;
  }

  .upload-demo {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: all 0.3s;

      &:hover {
        border-color: #409eff;
      }
    }

    .el-icon--upload {
      font-size: 67px;
      color: #c0c4cc;
      margin: 40px 0 16px;
      line-height: 50px;
    }

    .el-upload__text {
      color: #606266;
      font-size: 14px;
      text-align: center;

      em {
        color: #409eff;
        font-style: normal;
      }
    }
  }
}
</style>
